package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sky.constant.MessageConstant.*;

/**
 * @ClassNameOrderServiceImpl
 * @Description TODO
 * @Author钰玟
 * @Date2025/2/16 下午1:47
 * @Version 1.0
 **/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理业务异常(地址簿为空 、 购物车为空)
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if( addressBook == null){
            throw new AddressBookBusinessException(ADDRESS_BOOK_IS_NULL);
        }
        Long UserId = BaseContext.getCurrentId();
        List<ShoppingCart> list = shoppingCartMapper.list(ShoppingCart.builder().userId(UserId).build());
        if(list == null || list.size() == 0){
            throw new ShoppingCartBusinessException(SHOPPING_CART_IS_NULL);
        }
        //2.向订单表插入数据
        Orders order = new Orders();
        order.setUserId(UserId);
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        //其他属性的赋值
        order.setOrderTime(LocalDateTime.now());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setUserId(UserId);
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        order.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(order);

        List<OrderDetail> orderDetails = new ArrayList<>();
        //3.向订单明细表插入 多条数据
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(order.getId());//设置关联的订单Id
            orderDetails.add(orderDetail);
        }
        //统一插入订单明细
        orderDetailsMapper.insertList(orderDetails);


        //4.清空购物车数据
        shoppingCartMapper.deleteByUserId(UserId);



        //5. 封装 OrderSubmitVO 返回给前端
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(order.getId());
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderTime(order.getOrderTime());
        orderSubmitVO.setOrderAmount(order.getAmount());



        return orderSubmitVO;
    }




    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders=new Orders();
//        orders.setId(ordersDB.getId());
//        orders.setStatus(Orders.TO_BE_CONFIRMED);
//        orders.setPayStatus(Orders.PAID);
//        orders.setCheckoutTime(LocalDateTime.now());


//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED) // 订单状态，待接单
//                .payStatus(Orders.PAID) // 支付状态，已支付
//                .checkoutTime(LocalDateTime.now()) // 更新支付时间
//                .build();

//        orderMapper.update(orders);
        //调用PaySuccess方法，修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 商户订单号，也就是前端传过来的orderNumber参数
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        
        
        //通过webSocket向管理端发送 来单提醒
        Map map = new HashMap<>();
        map.put("type",1);//1表示订单来了
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        //转化成JSON字符串
        String json = JSON.toJSONString(map);
        //通过webSocket发送消息
        webSocketServer.sendToAllClient(json);

    }

    @Override
    public PageResult historyOrders(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        if(orders != null && !orders.isEmpty()){
            for (Orders order : orders) {
                OrderVO orderVO = new OrderVO();
                Long id = order.getId();
                List<OrderDetail> orderDetails = orderDetailsMapper.getOrderDetailsByOrderId(id);
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(orders.getTotal(), orderVOList);



//        // 设置分页
//        PageHelper.startPage(page, pageSize);
//
//        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
//        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
//        ordersPageQueryDTO.setStatus(status);
//
//        // 分页条件查询
//        Page<Orders> pageList = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        List<OrderVO> list = new ArrayList();
//
//        // 查询出订单明细，并封装入OrderVO进行响应
//        if (pageList != null && pageList.getTotal() > 0) {
//            for (Orders orders : pageList) {
//                Long orderId = orders.getId();// 订单id
//
//                // 查询订单明细
//                List<OrderDetail> orderDetails = orderDetailsMapper.getOrderDetailsByOrderId(orderId);
//
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//
//                list.add(orderVO);
//            }
//        }
//        return new PageResult(pageList.getTotal(), list);
    }

    @Override
    public OrderVO orderDetail(Long id) {
//        OrderVO orderVO = new OrderVO();
//        Orders order = orderMapper.getById(id);
//        List<OrderDetail> orderDetailsByOrderId = orderDetailsMapper.getOrderDetailsByOrderId(id);
//        BeanUtils.copyProperties(order,orderVO);
//        orderVO.setOrderDetailList(orderDetailsByOrderId);
//        return orderVO;

        // 根据id查询订单
        Orders orders = orderMapper.getById(id);
//        System.out.println("order:"+orders);
        orders.setAddress(getAddress(orders.getAddressBookId()));

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailsMapper.getOrderDetailsByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }
    //获取订单配送地址
    private String getAddress(Long addressBookId){
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        String address = addressBook.getProvinceName() + addressBook.getCityName() +
                addressBook.getDistrictName() + addressBook.getDetail();
        return address;
    }

    /**
     *  取消订单
     * @param id 订单id
     */
    @Override
    public void cancelOrder(Long id) {
        // 根据id查询订单
        Orders order = orderMapper.getById(id);
        //查看订单状态
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
        if(order.getStatus() >2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        order.setStatus(Orders.CANCELLED);
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 再来一单
     * @param id 订单id
     */
    @Override
    public void repetitionOrder(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailsMapper.getOrderDetailsByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(orders);




        return new PageResult(orders.getTotal(), orderVOList);

    }



    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailsMapper.getOrderDetailsByOrderId(orders.getId());

        // 将每一条 订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 获取订单统计信息
     * @return 订单统计信息
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        // 待接单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //待派送数量
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed( toBeConfirmed);
        orderStatisticsVO.setConfirmed( confirmed);
        orderStatisticsVO.setDeliveryInProgress( deliveryInProgress);


        return orderStatisticsVO;
    }

    /**
     * 确认订单
     * @param ordersConfirmDTO 订单确认信息
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        //修改订单状态
        orderMapper.update(Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build());
    }

    /**
     *  拒绝订单
     * @param ordersRejectionDTO 订单拒绝DTO 对象
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //只有待接单状态的订单才可以拒绝
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());
        Integer status = order.getStatus();
        if(order == null||status!=Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders updateOrder = Orders.builder()
                .id(order.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(updateOrder);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO 订单取消DTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        //只有待接单状态的订单才可以取消
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        Integer status = order.getStatus();


        Orders updateOrder = Orders.builder()
                .id(order.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(updateOrder);
    }

    /**
     * 派送订单
     * @param id 订单id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders order = orderMapper.getById(id);
        Integer status = order.getStatus();
        if(order == null||Orders.CONFIRMED !=status){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders updateOrder = Orders.builder()
                .id(order.getId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(updateOrder);
    }

    /**
     * 完成订单
     * @param id 订单id     完成订单
     */
    @Override
    public void completeOrder(Long id) {
        Orders order = orderMapper.getById(id);
        Integer status = order.getStatus();
        if(order == null||Orders.DELIVERY_IN_PROGRESS !=status){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders updateOrder = Orders.builder()
                .id(order.getId())
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(updateOrder);
    }

    /**
     * 用户催单
     * @param id 订单Id
     *
     */
    @Override
    public void reminderOrder(Long id) {
        Orders order = orderMapper.getById(id);
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //type orderId content
        Map map = new HashMap();
        map.put("type",2);//2表示用户催单
        map.put("orderId",id);
        map.put("content","订单号:"+order.getNumber());


        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }
}
